//
//  LOAppDelegate.m
//  LegalObserver
//
//  Created by Roxanne Brittain on 10/30/11.
//  Copyright (c) 2011 Digifit. All rights reserved.
//

#import "LOAppDelegate.h"
#import "IncidentListViewController.h"
#import "GuideViewController.h"
#import "PhotoListViewController.h"
#import "LOIncident.h"
#import "LOMedia.h"
#import "LOCoder.h"
#import <MessageUI/MFMailComposeViewController.h>
#import "FlurryAnalytics.h"

#define kImageDataArrayTag  @"imageDataArray"
#define kVideoURLArrayTag   @"videoURLArray"
#define kMediaArrayTag      @"mediaArray"
#define kIncidentArrayTag   @"incidents"

@implementation LOAppDelegate

@synthesize window = _window;
@synthesize tabBarController = _tabBarController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    UIViewController *viewController1 = [[IncidentListViewController alloc] initWithStyle:UITableViewStylePlain];
    UINavigationController *navController1 = [[UINavigationController alloc] initWithRootViewController:viewController1];

    UIViewController *viewController2 = [[GuideViewController alloc] initWithStyle:UITableViewStyleGrouped];
    UINavigationController *navController2 = [[UINavigationController alloc] initWithRootViewController:viewController2];

    UIViewController *viewController3 = [[PhotoListViewController alloc] initWithNibName:nil bundle:nil];
    UINavigationController *navController3 = [[UINavigationController alloc] initWithRootViewController:viewController3];
    
    navController1.navigationBar.tintColor = [UIColor redColor];
    navController2.navigationBar.tintColor = [UIColor redColor];
    navController3.navigationBar.tintColor = [UIColor redColor];
    
    self.tabBarController = [[UITabBarController alloc] init];
    self.tabBarController.tabBar.selectedImageTintColor = [UIColor redColor];
    self.tabBarController.viewControllers = [NSArray arrayWithObjects:navController1, navController2, navController3, nil];
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    
    
    [TestFlight takeOff:@"5d52609c69564c1de75208d639913ee0_MzEzNDcyMDExLTEwLTI4IDEwOjU4OjM1LjIwMTE4OA"];
    [FlurryAnalytics startSession:@"36E9GMSVQPEBPSKMCIXX"];
    
    return YES;
}

+(MFMailComposeViewController *)backupIncident:(LOIncident *)incident
{
    
    NSString *body = [incident stringDescription];
    body = [body stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
    NSLog(@"%@", [incident stringDescription]);
    
    if ([MFMailComposeViewController canSendMail] == FALSE) {
		[[[UIAlertView alloc] initWithTitle:@"No Email" message:@"This device is not set up to support email." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show];
		return nil;
	}
    
	MFMailComposeViewController *vc = [[MFMailComposeViewController alloc] init];
	
    [vc setSubject:@"Legal Observer Incident Report"];
//    [vc setToRecipients:[NSArray arrayWithObjects:@"", nil]];
	[vc setMessageBody:body isHTML:NO];
	
    return vc;
}

+(MFMailComposeViewController*)backupMedia:(LOMedia *)media
{
    NSString *body = [media stringDescription];
    body = [body stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
    NSLog(@"%@", body);
    
    if ([MFMailComposeViewController canSendMail] == FALSE) {
		[[[UIAlertView alloc] initWithTitle:@"No Email" message:@"This device is not set up to support email." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show];
		return nil;
	}
    
	MFMailComposeViewController *vc = [[MFMailComposeViewController alloc] init];
	
    [vc setSubject:@"Legal Observer Incident Report - Media"];
    //    [vc setToRecipients:[NSArray arrayWithObjects:@"", nil]];
	[vc setMessageBody:body isHTML:NO];
	
    if (media.type == MEDIA_TYPE_PHOTO) {
        NSData *imageData = UIImagePNGRepresentation(media.image);
        [vc addAttachmentData:imageData mimeType:@"image/png" fileName:@"lomedia.png"];
    } else if (media.type == MEDIA_TYPE_VIDEO) {
        NSData *data = [[NSData alloc] initWithContentsOfURL:media.videoURL];
        [vc addAttachmentData:data mimeType:@"video/quicktime" fileName:@"lomedia.mov"];
    }
    
    return vc;
}

+(NSString*) stringDescriptionForArray:(NSArray*)array
{
    NSMutableString *string = [NSMutableString new];
    for (id obj in array) {
        [string appendFormat:@"%@\n", [obj stringDescription]];
    }
    
    return [NSString stringWithString:string];
}

+(void)addImage:(UIImage *)image
{
    image = [self scaleAndRotateImage:image];
    
    LOMedia *media = [[LOMedia alloc] initWithImage:image];
    NSMutableArray *array = [self getMediaArray];
    [array addObject:media];
    [self saveMediaArray:array];
    
}

+(UIImage *)scaleAndRotateImage:(UIImage *)image
{
    int kMaxResolution = 320; // Or whatever
    
    CGImageRef imgRef = image.CGImage;
    
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);
    if (width > kMaxResolution || height > kMaxResolution) {
        CGFloat ratio = width/height;
        if (ratio > 1) {
            bounds.size.width = kMaxResolution;
            bounds.size.height = bounds.size.width / ratio;
            }
        else {
            bounds.size.height = kMaxResolution;
            bounds.size.width = bounds.size.height * ratio;
            }
        }
    
    CGFloat scaleRatio = bounds.size.width / width;
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
    CGFloat boundHeight;
    UIImageOrientation orient = image.imageOrientation;
    switch(orient) {
            
            case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;
            
            case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;
            
            case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
            case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;
            
            case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
            
            case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
            
            case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
            
            case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
            
            default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
            
        }
    
    UIGraphicsBeginImageContext(bounds.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
        }
    else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
        }
    
    CGContextConcatCTM(context, transform);
    
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return imageCopy;
}


+(void)addVideoURL:(NSURL *)videoURL
{
    NSMutableArray *array = [self getMediaArray];
    LOMedia *media = [[LOMedia alloc] initWithVideoURL:videoURL];
    [array addObject:media];
    [self saveMediaArray:array];
}

+(NSMutableArray *)getMediaArray
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *path = [paths objectAtIndex:0];
	NSString *af = [ NSString stringWithFormat:@"%@/%@.karch", path, kMediaArrayTag];
	
	NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:af];
    
    if (!array) {
        array = [[NSMutableArray alloc] init];
    }
    
    return array;
}

+(void)saveMediaArray:(NSMutableArray *)array{
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *path = [paths objectAtIndex:0];
	NSString *af = [ NSString stringWithFormat:@"%@/%@.karch", path, kMediaArrayTag];
	[NSKeyedArchiver archiveRootObject:array toFile:af];
}

+(NSMutableArray *)getIncidentArray
{
    //load data from archive file
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *path = [paths objectAtIndex:0];
	NSString *af = [ NSString stringWithFormat:@"%@/%@.karch", path, kIncidentArrayTag];
	
	NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:af];
    
    if (!array) {
        array = [[NSMutableArray alloc] init];
    }
    
    return array;
}

+(void)saveIncidentArray:(NSMutableArray *)array{
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *path = [paths objectAtIndex:0];
	NSString *af = [ NSString stringWithFormat:@"%@/%@.karch", path, kIncidentArrayTag];
	[NSKeyedArchiver archiveRootObject:array toFile:af];
}

+(NSString *)stringFromDate:(NSDate *)date
{
    return [self stringFromDate:date withTime:YES];
}

+(NSString *)stringFromDate:(NSDate *)date withTime:(BOOL)time
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    if (time) [df setDateFormat:@"M/dd/yy  h:mm a"];
    else [df setDateFormat:@"M/dd/yy"];
    
    return [df stringFromDate:date];
}

+(NSDate *)dateFromString:(NSString *)string
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"M/dd/yy  h:mm a"];
    
    return [df dateFromString:string];
}

+(NSString *)stringFromDate:(NSDate *)date withFormat:(NSString *)format
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:format];
    
    return [df stringFromDate:date];
}

+(NSDate *)dateFromString:(NSString *)string withFormat:(NSString *)format
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:format];
    
    return [df dateFromString:string];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [TestFlight passCheckpoint:@"didBecomeActive"];
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
}
*/

/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed
{
}
*/

@end
